//
//  BBuyNowShopDetailContentCell.m
//  DistributorAB
//
//  Created by LZY on 2019/10/9.
//  Copyright © 2019 主事丫环. All rights reserved.
//

#import "BBuyNowShopDetailContentCell.h"
#import "ZTagListYellowView.h"//黄色标签
#import "ZTagListView.h"

@interface BBuyNowShopDetailContentCell () <ZTagListViewDelegate,UITextFieldDelegate>
@property (nonatomic, strong) UILabel *lblTitle;//标题
@property (nonatomic, strong) ZTagListYellowView *viewYellowTag;//选中的标签view
@property (nonatomic, strong) UILabel *lblPriceSelected;//选中型号价格(省级显示)
@property (nonatomic, strong) UILabel *lblSelected;//选中型号
@property (nonatomic, strong) UIButton *btnArrow;//展开按钮
@property (nonatomic, strong) ZTagListView *viewTag;//型号标签view
@property (nonatomic, strong) UITextField *tfBuy;//购买量
@property (nonatomic, strong) UIButton *btnLeft;//-
@property (nonatomic, strong) UIButton *btnRight;//+
@property (nonatomic, strong) BShopPartTypeModel *typeModelSelected;//记录选中的标签
@property (nonatomic, strong) UIView *viewLineOne;//中间的分割线
@property (nonatomic, strong) UILabel *lblType;//选择型号 文字

@end

@implementation BBuyNowShopDetailContentCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setupViewAction];
    }
    return self;
}
#pragma mark - 界面布局
- (void)setupViewAction{
    self.contentView.backgroundColor = kColorWithHex(0xffffff);
    
    _lblTitle = [UILabel new];
    _lblTitle.textColor = kColorWithHex(0x333333);
    _lblTitle.font = [UIFont systemFontOfSize:16];
    _lblTitle.numberOfLines = 2;
    _lblTitle.preferredMaxLayoutWidth = kScreen_Width - 39;
    [self.contentView addSubview:_lblTitle];
    [_lblTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView.mas_top).offset(7);
        make.leading.equalTo(self.contentView.mas_leading).offset(16);
        make.trailing.equalTo(self.contentView.mas_trailing).offset(-23);
        make.height.mas_equalTo(24);
    }];
    
    if (AGENT_LEVEL == 1) {
        _lblPriceSelected = [UILabel new];
        _lblPriceSelected.font = [UIFont boldSystemFontOfSize:20];
        _lblPriceSelected.textColor = kColorWithHex(0x70be68);
        [self.contentView addSubview:_lblPriceSelected];
        [_lblPriceSelected mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.equalTo(self.lblTitle);
            make.top.equalTo(self.lblTitle.mas_bottom).offset(7);
        }];
    }
    
    _viewYellowTag = [ZTagListYellowView new];
    _viewYellowTag.width = kScreen_Width;
    [self.contentView addSubview:_viewYellowTag];
    [_viewYellowTag mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.contentView);
        if (AGENT_LEVEL == 1) {
            make.top.equalTo(self.lblPriceSelected.mas_bottom).offset(7);
        }else{
            make.top.equalTo(self.lblTitle.mas_bottom);
        }
        make.height.mas_equalTo(0);
    }];
    
    UIView *viewLineOne = [UIView new];
    viewLineOne.backgroundColor = kColorWithHex(0xf2f2f2);
    [self.contentView addSubview:viewLineOne];
    [viewLineOne mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.contentView);
        make.top.equalTo(self.viewYellowTag.mas_bottom).offset(14);
        make.height.mas_equalTo(2);
    }];
    self.viewLineOne = viewLineOne;
    
    UILabel *lblType = [UILabel new];
    lblType.text = @"选择型号";
    lblType.font = [UIFont systemFontOfSize:14];
    lblType.textColor = kColorWithHex(0x777777);
    [self.contentView addSubview:lblType];
    [lblType mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.contentView.mas_leading).offset(16);
        make.top.equalTo(viewLineOne.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(60, 44));
    }];
    self.lblType = lblType;
    
    _lblSelected = [UILabel new];
    _lblSelected.text = @"请选择";
    _lblSelected.font = [UIFont systemFontOfSize:14];
    _lblSelected.textColor = kColorWithHex(0x333333);
    [self.contentView addSubview:_lblSelected];
    [_lblSelected mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(viewLineOne.mas_bottom);
        make.leading.equalTo(lblType.mas_trailing).offset(13);
        make.trailing.equalTo(self.contentView.mas_trailing).offset(-60);
        make.height.equalTo(@(44));
    }];
   
    
    _btnArrow = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btnArrow setImage:imgname(@"arrow_down_icon") forState:UIControlStateNormal];
    [_btnArrow setImage:imgname(@"arrow_up_icon") forState:UIControlStateSelected];
    [_btnArrow addTarget:self action:@selector(btnArrowClickAction:) forControlEvents:UIControlEventTouchUpInside];
    _btnArrow.selected = NO;
    [self.contentView addSubview:_btnArrow];
    [_btnArrow mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(lblType.mas_centerY);
        make.trailing.equalTo(self.contentView.mas_trailing).offset(-9);
        make.size.mas_equalTo(CGSizeMake(45, 45));
    }];
    
    _viewTag = [ZTagListView new];
    _viewTag.tag_delegate = self;
    _viewTag.width = kScreen_Width;
    [self.contentView addSubview:_viewTag];
    [_viewTag mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.contentView);
        make.top.equalTo(lblType.mas_bottom);
        make.height.mas_equalTo(0);
    }];
    
    UIView *viewLineTwo = [UIView new];
    viewLineTwo.backgroundColor = kColorWithHex(0xf2f2f2);
    [self.contentView addSubview:viewLineTwo];
    [viewLineTwo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.contentView);
        make.top.equalTo(self.viewTag.mas_bottom);
        make.height.mas_equalTo(2);
    }];
    
    UILabel *lblNumberNotice = [UILabel new];
    lblNumberNotice.text = @"数量";
    lblNumberNotice.font = [UIFont systemFontOfSize:14];
    lblNumberNotice.textColor = kColorWithHex(0x333333);
    [self.contentView addSubview:lblNumberNotice];
    [lblNumberNotice mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.contentView.mas_leading).offset(16);
        make.top.equalTo(viewLineTwo.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(30, 50));
    }];
    
    _btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btnRight setTitle:@"+" forState:UIControlStateNormal];
    [_btnRight setTitleColor:kColorWithHex(0x999999) forState:UIControlStateNormal];
    _btnRight.titleLabel.font = [UIFont systemFontOfSize:14];
    [_btnRight addTarget:self action:@selector(btnRightClickAction:) forControlEvents:UIControlEventTouchUpInside];
    _btnRight.layer.borderColor = kColorWithHex(0x707070).CGColor;
    _btnRight.layer.borderWidth = 1;
    _btnRight.layer.cornerRadius = 2;
    _btnRight.layer.masksToBounds = YES;
    [self.contentView addSubview:_btnRight];
    [_btnRight mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.contentView.mas_trailing).offset(-16);
        make.centerY.equalTo(lblNumberNotice.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(32, 24));
    }];
    
    _tfBuy = [UITextField new];
    _tfBuy.text = @"0";
    _tfBuy.font = [UIFont systemFontOfSize:14];
    _tfBuy.textColor = kColorWithHex(0x979797);
    _tfBuy.textAlignment = NSTextAlignmentCenter;
    _tfBuy.layer.borderColor = kColorWithHex(0x707070).CGColor;
    _tfBuy.layer.borderWidth = 1;
    _tfBuy.keyboardType = UIKeyboardTypeNumberPad;
    _tfBuy.delegate = self;
    [self.contentView addSubview:_tfBuy];
    [_tfBuy mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.btnRight.mas_leading);
        make.centerY.equalTo(lblNumberNotice.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(60, 24));
    }];
    
    
    _btnLeft = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btnLeft setTitle:@"-" forState:UIControlStateNormal];
    [_btnLeft setTitleColor:kColorWithHex(0xdddbd7) forState:UIControlStateNormal];;
    _btnLeft.titleLabel.font = [UIFont systemFontOfSize:14];
    [_btnLeft addTarget:self action:@selector(btnLeftClickAction:) forControlEvents:UIControlEventTouchUpInside];
    _btnLeft.layer.borderColor = kColorWithHex(0x707070).CGColor;
    _btnLeft.layer.borderWidth = 1;
    _btnLeft.layer.cornerRadius = 2;
    _btnLeft.layer.masksToBounds = YES;
    [self.contentView addSubview:_btnLeft];
    [_btnLeft mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.tfBuy.mas_leading);
        make.centerY.equalTo(lblNumberNotice.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(32, 24));
    }];
    
    UIView *viewLineThree = [UIView new];
    viewLineThree.backgroundColor = kColorWithHex(0xf2f2f2);
    [self.contentView addSubview:viewLineThree];
    [viewLineThree mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.contentView);
        make.top.equalTo(lblNumberNotice.mas_bottom);
        make.height.mas_equalTo(10);
        make.bottom.equalTo(self.contentView.mas_bottom);
    }];
    if (AGENT_LEVEL ==2) {
        viewLineTwo.hidden = YES;
        lblNumberNotice.hidden = YES;
        _btnRight.hidden = YES;
        _tfBuy.hidden = YES;
        _btnLeft.hidden = YES;
        viewLineThree.hidden = YES;
    }
}
#pragma mark - 数据更新
- (void)setPartModel:(BShopPartDetailModel *)partModel{
    if (partModel) {
        kWeakSelf;
        
        _partModel = partModel;
        
        _lblTitle.text = partModel.parts_details;
        CGSize sizeLbl = [_lblTitle.text sizeWithAttributes:@{NSFontAttributeName:_lblTitle.font}];
        [_lblTitle mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(sizeLbl.height);
        }];
        
        NSArray *attributeArr = partModel.attribute;
        NSMutableArray *tagArr = [NSMutableArray array];
        __block NSMutableArray *attributeTagArr = [NSMutableArray array];
        [attributeArr enumerateObjectsUsingBlock:^(BShopPartTypeModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [tagArr addObjectNotNil:obj.name];
            //如果类型被选中
            if (obj.isSelected) {
                if (obj.compensationPrice.length > 0 && [obj.compensationPrice integerValue]>0) {
                    [attributeTagArr addObject:[NSString stringWithFormat:@"补贴工时费 ￥%@/个",obj.compensationPrice]];
                }
                if (obj.warranty.length > 0 && [obj.warranty integerValue]>0) {
                    [attributeTagArr addObject:[NSString stringWithFormat:@"质保期 %@个月",obj.warranty]];
                }
                if (obj.install.length > 0 && [obj.install integerValue]>0) {
                    [attributeTagArr addObject:[NSString stringWithFormat:@"自出厂日期有效期为%@个月",obj.install]];
                }
                
                [weakSelf.viewYellowTag setupSubviewWithTitles:attributeTagArr];
                partModel.attributeSelectedHeight = weakSelf.viewYellowTag.contentSize.height > 0 ? weakSelf.viewYellowTag.contentSize.height : partModel.attributeSelectedHeight;
                [weakSelf.viewYellowTag mas_updateConstraints:^(MASConstraintMaker *make) {
                   make.height.mas_equalTo(partModel.attributeSelectedHeight);
                    if (attributeTagArr.count<3) {
                        make.top.equalTo(self.lblTitle.mas_bottom).offset(8);
                        
                    }
                }];
                
                weakSelf.typeModelSelected = obj;
                weakSelf.viewTag.selectedIndex = idx + 1;
                
                weakSelf.lblPriceSelected.text = [NSString stringWithFormat:@"￥%@",obj.salePrice];
                weakSelf.lblSelected.text = [NSString stringWithFormat:@"已选择 %@",obj.name];
                weakSelf.tfBuy.text = obj.quantity;
                weakSelf.partModel.buyNumber = [obj.quantity integerValue];
            
                [self.lblType mas_updateConstraints:^(MASConstraintMaker *make) {
                   make.centerY.equalTo(self.lblSelected);
                }];
            }
        }];
        
        [_viewTag setupSubviewWithTitles:tagArr];
        partModel.attributeHeight = partModel.attributeHeight > 0 ? partModel.attributeHeight : self.viewTag.contentSize.height + 20;
        [_viewTag mas_updateConstraints:^(MASConstraintMaker *make) {
            if (partModel.isOpenAttribute) {
                make.height.mas_equalTo(partModel.attributeHeight);
            }else{
                make.height.mas_equalTo(0);
            }
        }];
        
    }
}
#pragma mark - 交互事件
//展开按钮
- (void)btnArrowClickAction:(UIButton *)sender{
    self.partModel.isOpenAttribute = !self.partModel.isOpenAttribute;
    _btnArrow.selected = !self.partModel.isOpenAttribute;
    if (self.delegate && [self.delegate respondsToSelector:@selector(buyNowShopDetailContentCellBtnArrowClick)]) {
        [self.delegate buyNowShopDetailContentCellBtnArrowClick];
    }
}

//+
- (void)btnRightClickAction:(UIButton *)sender{
    if (self.partModel && self.typeModelSelected) {
        self.partModel.buyNumber++;
        self.tfBuy.text = [NSString stringWithFormat:@"%ld",(long)self.partModel.buyNumber];
        [self.btnLeft setTitleColor:kColorWithHex(0x999999) forState:UIControlStateNormal];
    }else{
        ShowToastWithText(@"请选择型号");
    }
}
//-
- (void)btnLeftClickAction:(UIButton *)sender{
    if (self.partModel && self.typeModelSelected) {
        NSInteger lowNumber = [self.typeModelSelected.quantity integerValue];;
        if (self.partModel.buyNumber > lowNumber) {
            self.partModel.buyNumber--;
            self.tfBuy.text = [NSString stringWithFormat:@"%ld",(long)self.partModel.buyNumber];
        }
        if (self.partModel.buyNumber <= lowNumber) {
            [self.btnLeft setTitleColor:kColorWithHex(0xdddbd7) forState:UIControlStateNormal];
            NSString *noticeStr = [NSString stringWithFormat:@"该产品最低购买%ld个",(long)lowNumber];
            ShowToastWithText(noticeStr);
        }
    }else{
        ShowToastWithText(@"请选择型号");
    }
}

#pragma mark - ZTagListViewDelegate
- (void)tagListView:(ZTagListView *_Nullable)tagListView didSelectedTagAtIndex:(NSInteger)index selectedContent:(NSString *_Nonnull)content{
    NSArray *attributeArr = self.partModel.attribute;
    
    BShopPartTypeModel *tagModel = [attributeArr objectAtIndexSafe:index];
    
    NSMutableArray *attributeTagArr = [NSMutableArray array];
    if (tagModel.compensationPrice.length > 0 && [tagModel.compensationPrice integerValue]>0) {
        [attributeTagArr addObject:[NSString stringWithFormat:@"补贴工时费 ￥%@/个",tagModel.compensationPrice]];
    }
    if (tagModel.warranty.length > 0 && [tagModel.warranty integerValue]>0) {
        [attributeTagArr addObject:[NSString stringWithFormat:@"质保期 %@个月",tagModel.warranty]];
    }
    if (tagModel.install.length > 0 && [tagModel.install integerValue]>0) {
        [attributeTagArr addObject:[NSString stringWithFormat:@"自出厂日期有效期为%@个月",tagModel.install]];
    }
    
    [self.viewYellowTag setupSubviewWithTitles:attributeTagArr];
    self.partModel.attributeSelectedHeight = self.viewYellowTag.contentSize.height > 0 ? self.viewYellowTag.contentSize.height : self.partModel.attributeSelectedHeight;
    [self.viewYellowTag mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.partModel.attributeSelectedHeight);
        if (attributeTagArr.count<3) {
            make.top.equalTo(self.lblTitle.mas_bottom).offset(8);
            
        }
    }];
    
    _lblPriceSelected.text = [NSString stringWithFormat:@"￥%@",tagModel.salePrice];
    _lblSelected.text = [NSString stringWithFormat:@"已选择 %@",tagModel.name];
    _tfBuy.text = tagModel.quantity;
    
    //取消原来的选中
    self.typeModelSelected.isSelected = NO;
    //设置新的选中
    tagModel.isSelected = YES;
    self.typeModelSelected = tagModel;
    self.partModel.buyNumber = [tagModel.quantity integerValue];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(buyNowShopDetailContentCellSelectedType:)]) {
        [self.delegate buyNowShopDetailContentCellSelectedType:tagModel];
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(buyNowShopDetailContentCellBtnArrowClick)]) {
        [self.delegate buyNowShopDetailContentCellBtnArrowClick];
    }
    
    [self.lblType mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.lblSelected);
    }];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (self.typeModelSelected) {
        return YES;
    }else{
        return NO;
    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < string.length) {
        NSString *str = [string substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [str rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    NSString *numberStr = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    NSInteger lowNumber = [self.typeModelSelected.quantity integerValue];
    if ([numberStr integerValue] > lowNumber) {
        self.partModel.buyNumber = [numberStr integerValue];
        self.tfBuy.text = [NSString stringWithFormat:@"%ld",(long)self.partModel.buyNumber];
    }
    if (self.partModel.buyNumber < lowNumber) {
        self.tfBuy.text = [NSString stringWithFormat:@"%ld",(long)lowNumber];
        [self.btnLeft setTitleColor:kColorWithHex(0xdddbd7) forState:UIControlStateNormal];
        NSString *noticeStr = [NSString stringWithFormat:@"该产品最低购买%ld个",(long)lowNumber];
        ShowToastWithText(noticeStr);
    }
}

- (CGFloat)cellHeight{
    //选中标签 高度
    CGFloat selectedTagHeight = self.partModel.attributeSelectedHeight;
    //标签高度
    CGFloat tagHeight = self.partModel.isOpenAttribute ? self.partModel.attributeHeight : 0.0;
    //文本高度
    CGSize sizeLbl = [_lblTitle.text sizeWithAttributes:@{NSFontAttributeName:_lblTitle.font}];
    if (AGENT_LEVEL ==2) {
        return 137-70 + tagHeight + sizeLbl.height + selectedTagHeight + 14;
    }
    return 137 + tagHeight + sizeLbl.height + selectedTagHeight + 14;
}
- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
